package com.org.netty.rpc.nettyStarter;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.concurrent.Callable;

/**
 * @author: Lixy
 * @email: 1908598362@qq.com
 * @date: 2022/2/11 星期五 19:53
 */
public class nettyClientHandler extends ChannelInboundHandlerAdapter implements Callable {


    private ChannelHandlerContext context;//上下文 方便其他方法调用另外一个方法的ctx
    private volatile String result;//结果
    private String param;//参数

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        context = ctx;

    }

    @Override
    public synchronized void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        result = msg.toString();
        notify();//唤醒等待 阻塞的线程

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

        ctx.close();

    }

    @Override
    public synchronized Object call() throws Exception {
        context.writeAndFlush(param);
        wait();
        return result;
    }


    void setParam(String param){
        this.param=param;
    }

}
